package com.cgl.controller;

import ch.qos.logback.core.model.INamedModel;
import com.auth0.jwt.interfaces.Claim;
import com.cgl.pojo.Comment;
import com.cgl.pojo.Result;
import com.cgl.service.CommentService;
import com.cgl.until.JwtUntil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class CommentController {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private CommentService commentService;
    @PostMapping("api/comment/add")
    public Result addComments(HttpServletRequest request, @RequestBody Comment comment){
        logger.info("添加评论:{},{}",comment,request.getHeader("LY-Authorization"));
        String token;
        try {
            token = request.getHeader("LY-Authorization").replace("\"", "");
        }catch (NullPointerException e){
            return Result.error("用户未登录");
        }
        logger.info("用户登录:{}", token);

        if (!JwtUntil.verifyToken(token)){
            return Result.error("timeover");
        }

        Map<String, Claim> data = JwtUntil.decodeToken(token);

        logger.info("解码的JWT声明: {}", data);

        String userId = data.get("userId").asString();

        comment.setUserId(userId);

        if(comment.equals("")){
            return Result.error("评论不能为空");
        }
        else {
            if (commentService.addComments(comment)){
                return Result.success();
            }
            else {
                return Result.error("评论失败");
            }
        }
    }
    @GetMapping("comment/getlist")
    public Result getCommentList(String articleId,Integer pageIndex,Integer pageSize){
        logger.info("获取评论列表:{},{},{}",articleId,pageIndex,pageSize);
        if (articleId.equals("")|| pageIndex==null||pageSize==null){
            return Result.error("参数错误");
        }
        if (pageIndex<0||pageSize<0){
            return Result.error("参数错误");
        }
        return Result.success(commentService.selectAll(articleId,pageIndex,pageSize));
    }

}
